﻿using Api.Shared.Model.Web.Login;
using Api.Shared.Sugar;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class RightsController : ControllerBase
    {
        private readonly ISugarClientService helper;

        public RightsController([FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper)
        {
            this.helper = helper;
        }
        [HttpGet]
        public async Task<IActionResult> GetList()
        {
            var rights = await this.helper.Db.Queryable<MenuItemNew>().ToListAsync();
            if (rights.Count == 0)
            {
                return StatusCode(204, "Failed");
            }
            else
            {
                return Ok(rights);
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetTree()
        {
            var menus = await this.helper
                .Db.Queryable<MenuItemNew>()
                .Where(x => x.level == 1).ToListAsync();

            foreach (var item1 in menus)
            {
                var menus2 = await this.helper
                .Db.Queryable<MenuItemNew>().Where(x => x.level == 2).ToListAsync();
                //二级菜单
                item1.children = menus2.Where(x =>
                x.parentMenuItemId
                .Split(',')
                .Contains(item1.id.ToString()))
                .ToList();
            }

            foreach (var item1 in menus)
            {
                foreach (var item2 in item1.children)
                {
                    var menus3 = await this.helper
                        .Db.Queryable<MenuItemNew>().Where(x => x.level == 3).ToListAsync();

                    //三级菜单
                    item2.children = menus3.Where(x =>
                    x.parentMenuItemId
                    .Split(',')
                    .Contains(item2.id.ToString())).ToList();
                }
            }

            if (menus != null)
            {
                return Ok(menus);
            }
            return StatusCode(204, "Failed");
        }
    }
}
